<?php
/**
* @file PortaMx.php
* The main programm for PortaMx.
*
* @author PortaMx - Portal Management Extension
* @author Copyright 2008-2011 by PortaMx - http://portamx.com
* @Version: 1.0 RC4
* @Date: 23.02.2011
*/

if(!defined('SMF'))
	die('This Portamx file can\'t be run without SMF');

/**
* Init all variables and load the settings from the database.
* Check the requests and prepare the templates to load.
*/
function PortaMx($CalledFrom = '')
{
	global $smcFunc, $pmxCacheFunc, $context, $settings, $db_character_set, $modSettings, $sourcedir, $boarddir, $boardurl, $txt, $mbname, $scripturl, $user_info;

	if(defined('PortaMx'))
		return;

	// we can exit on this...
	if(isset($_REQUEST['action']) && ($_REQUEST['action'] == 'dlattach' && $CalledFrom != 'Sec'))
		return;

	define('PortaMx', 1);

	// setup dirs
	$context['pmx_sourcedir'] = $sourcedir .'/PortaMx/';
	$context['pmx_classdir'] = $sourcedir .'/PortaMx/Class/';
	$context['pmx_sysclassdir'] = $sourcedir .'/PortaMx/Class/System/';
	$context['pmx_templatedir'] = 'PortaMx/';
	$context['pmx_customcssdir'] = $settings['default_theme_dir'] .'/PortaMx/BlockCss/';
	$context['pmx_syscssdir'] = $settings['default_theme_dir'] .'/PortaMx/SysCss/';
	$context['pmx_languagedir'] = $settings['default_theme_dir'] .'/languages/PortaMx/';

	// .. urls
	$context['pmx_imageurl'] = $settings['default_theme_url'] .'/PortaMx/SysCss/Images/';
	$context['pmx_syscssurl'] = $settings['default_theme_url'] .'/PortaMx/SysCss/';
	$context['pmx_customcssurl'] = $settings['default_theme_url'] .'/PortaMx/BlockCss/';
	$context['pmx_scripturl'] = $settings['default_theme_url'] .'/PortaMx/Scripts/';

	// title icons link/path
	$context['pmx_Iconsurl'] = $settings['default_theme_url'] .'/PortaMx/TitleIcons/';
	$context['pmx_Iconsdir'] = $settings['default_theme_dir'] .'/PortaMx/TitleIcons/';

	// check if utf8 charset used
	$context['pmx']['uses_utf8'] = ((isset($modSettings['global_character_set']) && $modSettings['global_character_set'] == 'UTF-8') || (isset($db_character_set) && $db_character_set == 'utf8'));

	// check if old core theme
	$context['pmx_style_isCore'] = (bool) (stripos(str_replace('\\', '/', $settings['theme_dir'] .'/'), '/core/') !== false);

	// load common language
	loadLanguage($context['pmx_templatedir'] .'PortaMx');

	// load require file
	require_once($context['pmx_sourcedir'] .'LoadData.php');
	require_once($context['pmx_sourcedir'] .'Compat.php');
	require_once($context['pmx_sysclassdir']. 'PortaMx_BlocksClass.php');

	// check if a language change requested
	if(isset($_REQUEST['language']) && isset($_REQUEST['pmxrd']))
		redirectexit(base64_decode($_REQUEST['pmxrd']));

	// redirect on illegal request
	if(!empty($_REQUEST['pmxportal']) || !empty($_REQUEST['pmxsef']) || (!empty($_REQUEST['pmxerror']) && !empty($_REQUEST['action'])))
		redirectexit('pmxerror=unknown');

	// check if a permanent theme change requested
	if(isset($_REQUEST['theme']) && isset($_REQUEST['pmxrd']))
		PortaMx_ChangeTheme($_REQUEST['theme'], $_REQUEST['pmxrd']);

	// load the SSI.php
	require_once($boarddir .'/SSI.php');

	// get all settings
	$context['pmx_head'] = substr(file_get_contents(__FILE__), 0, 256);
	PortaMx_getSettings();

	// setup upskrink images
	if(!isset($context['pmx']['settings']['shrinkimages']))
		$context['pmx']['settings']['shrinkimages'] = 0;
	if(!empty($context['pmx']['settings']['shrinkimages']) && $context['pmx']['settings']['shrinkimages'] == 1)
	{
		$context['pmx_img_expand'] = $settings['theme_url'] .'/images/collapse.gif';
		$context['pmx_img_colapse'] = $settings['theme_url'] .'/images/expand.gif';
	}
	else
	{
		$context['pmx_img_expand'] = $context['pmx_imageurl'] .'collapse.gif';
		$context['pmx_img_colapse'] = $context['pmx_imageurl'] .'expand.gif';
	}
	$context['pmx']['show_forum_button'] = $context['pmx']['settings']['frontpage'] != 'none';

	// setup all block sides
	$context['pmx']['block_sides'] = array_keys($txt['pmx_block_sides']);

	// setup panel collapse, xbars and xbarkeys
	foreach($context['pmx']['block_sides'] as $side)
	{
		if($side != 'front')
		{
			$context['pmx']['xbar_'.$side] = isset($context['pmx']['settings']['xbars']) && in_array($side, array_values($context['pmx']['settings']['xbars']));
			$context['pmx']['xbarkeys'] = isset($context['pmx']['settings']['xbarkeys']) && !empty($context['pmx']['settings']['xbarkeys']);
			$context['pmx']['collapse'][$side] = empty($context['pmx']['settings'][$side.'_panel']['collapse']) && ($context['pmx']['xbar_'.$side] || $context['pmx']['xbarkeys']);
		}
	}

	// exit on follow actions or wireless
	if(WIRELESS || $CalledFrom == 'SSI' || isset($_REQUEST['xml']) || isset($_REQUEST['action']) && in_array($_REQUEST['action'], array('jseditor', 'jsoption', '.xml', 'xmlhttp', 'dlattach', 'verificationcode', 'printpage')))
		return;

	// handle SimpleDesk ajax request
	if(!empty($modSettings['helpdesk_active']) && !empty($_REQUEST['sa']) && $_REQUEST['sa'] == 'ajax')
		return;

	// exit on external login with redirect
	if(isset($_REQUEST['action']) && $_REQUEST['action'] == 'login' && isset($_SESSION['old_url']) && preg_match('~(board|topic)[=,]~', $_SESSION['old_url']) != 0)
		return;

	// load common javascript
	$cookparts = pmx_getcookparts();
	$context['html_headers'] .= '
	<script language="JavaScript" type="text/javascript"><!-- // --><![CDATA[
		function Pmx_Cookie(sName, sValue, sExpiry) {
			document.cookie = sName + "=" + sValue + ";domain='. $cookparts['host'] .';path='. $cookparts['path'] .'" + (sExpiry ? ";expires=" + sExpiry.toGMTString() : "");
		}
		var pmx_popup_rtl = '. (!empty($context['right_to_left']) ? 'true;' : 'false;') .'
	// ]]></script>
	<script language="JavaScript" type="text/javascript" src="'. $context['pmx_scripturl'] .'PortaMx.js"></script>';

	// on Admin or Moderate load admin language and javascript
	if(isset($_REQUEST['action']) && ($_REQUEST['action'] == 'admin' || $_REQUEST['action'] == 'portamx') && isset($_REQUEST['area']) && in_array($_REQUEST['area'], explode(',', $context['pmx']['areas'])))
	{
		// load the admin javascrip
		$context['html_headers'] .= '
	<script language="JavaScript" type="text/javascript" src="'. $context['pmx_scripturl'] .'PortaMxAdmin.js"></script>';

		// admin languages
		loadLanguage($context['pmx_templatedir'] .'Admin');
	}

	// check Error request, Forum request
	$context['pmx']['forumReq'] = empty($_REQUEST['pmxerror']) && (!empty($_REQUEST['action']) || !empty($context['current_board']) || !empty($context['current_topic']));
	if(empty($context['pmx']['forumReq']) && !empty($context['pmx']['settings']['other_actions']))
	{
		$reqtyp = Pmx_StrToArray($context['pmx']['settings']['other_actions']);
		foreach($reqtyp as $rtyp)
		{
			@list($rtyp, $rval) = Pmx_StrToArray($rtyp, '=');
			$context['pmx']['forumReq'] = ($context['pmx']['forumReq'] || (isset($_REQUEST[$rtyp]) && (is_null($rval) || $_REQUEST[$rtyp] == $rval)));
		}
	}

	// check Page, category, article request
	$pmxRequestTypes = array('spage', 'art', 'cat', 'child');
	$context['pmx']['pageReq'] = array();
	foreach($pmxRequestTypes as $type)
	{
		if(empty($_REQUEST['action']) && !empty($_REQUEST[$type]))
			$context['pmx']['pageReq'][$type] = PortaMx_makeSafe($_REQUEST[$type]);
	}

  if(empty($context['pmx']['forumReq']) && empty($context['pmx']['pageReq']) && $context['pmx']['settings']['frontpage'] == 'none')
	{
		$_REQUEST['action'] = $_GET['action'] = 'community';
		$context['pmx']['forumReq'] = true;
	}

	// Disable HighSlide on action?
	if(isset($_REQUEST['action']) && isset($context['pmx']['settings']['noHS_onaction']))
	{
		$noHighSlide = isset($context['pmx']['settings']['noHS_onaction']) ? Pmx_StrToArray($context['pmx']['settings']['noHS_onaction']) : array();
		if(in_array($_REQUEST['action'], $noHighSlide))
			$context['pmx']['settings']['disableHS'] = 1;
	}

	// Admin panel/block hidding ?
	$hideRequest = array_intersect($context['pmx']['extracmd'] , array_keys($_REQUEST));
	if(!empty($hideRequest) && allowPmx('pmx_admin'))
	{
		@list($hideRequest) = array_values($hideRequest);
		$mode = substr($hideRequest, 5);
		$hidetyp = substr($hideRequest, 0, 5);
		$offparts = empty($modSettings['pmx_'. $hidetyp .'off']) ? array() : Pmx_StrToArray($modSettings['pmx_'. $hidetyp .'off']);
		if($mode == 'off')
		{
			if($hidetyp == 'panel')
				$offparts = array_intersect(($_REQUEST[$hideRequest] == 'all' ? $context['pmx']['block_sides'] : array_merge($offparts, Pmx_StrToArray($_REQUEST[$hideRequest]))), $context['pmx']['block_sides']);
			else
				$offparts = array_merge($offparts, Pmx_StrToIntArray($_REQUEST[$hideRequest]));
		}
		else
		{
			if($hidetyp == 'panel')
				$offparts = array_intersect(($_REQUEST[$hideRequest] == 'all' ?  array() : array_diff($offparts, Pmx_StrToArray($_REQUEST[$hideRequest]))), $context['pmx']['block_sides']);
			else
				$offparts = $_REQUEST[$hideRequest] == 'all' ?  array() : array_diff($offparts, Pmx_StrToIntArray($_REQUEST[$hideRequest]));
		}
		updateSettings(array('pmx_'. $hidetyp .'off' => implode(',', $offparts)));
		unset($_GET[$hideRequest]);
		redirectexit(pmx_http_build_query($_GET));
	}

	// check all the actions and more...
  if(empty($context['pmx']['forumReq']))
	{
		// if a redirect request, exit
		$requrl = (strpos($_SERVER['REQUEST_URL'], substr($scripturl, 0, strrpos($scripturl, '/'))) === false ? $_SERVER['REQUEST_URL'] : $scripturl);
		if(substr($requrl, 0, strrpos($requrl, '/')) != substr($scripturl, 0, strrpos($scripturl, '/')))
			return;

		// we use the frontpage ?
		$useFront = ($context['pmx']['settings']['frontpage'] == 'none' && empty($context['pmx']['pageReq']) && empty($_GET['pmxerror'])) ? '' : 'frontpage';

		// get all block on active panels they can view
		$context['pmx']['viewblocks'] = getPanelsToShow($useFront);

		// frontpage and/or Page blocks exist ?
		if(empty($useFront) || !empty($context['pmx']['show_frontpanel']) || !empty($context['pmx']['show_pagespanel']) || !empty($_GET['pmxerror']))
		{
			// disable HighSlide on Frontpage?
			if(!empty($context['pmx']['settings']['disableHSonfront']))
				$context['pmx']['settings']['disableHS'] = true;

			// setup headers
			PortaMx_headers('frontpage');
			$context['robot_no_index'] = (empty($context['pmx']['settings']['indexfront']));

			if($context['pmx']['settings']['frontpage'] == 'fullsize')
			{
				loadTemplate($context['pmx_templatedir'] .'Frontpage'. ($context['pmx_style_isCore'] ? '_core' : ''));
				$context['template_layers'] = array('fronthtml', 'portamx');
			}
			else
			{
				loadTemplate($context['pmx_templatedir'] .'Mainindex');
				$context['template_layers'][] = 'portamx';
			}
			if(!empty($context['pmx']['pageReq']) || !empty($_GET['pmxerror']) || (empty($context['pmx']['forumReq']) && $context['pmx']['settings']['frontpage'] != 'none'))
				loadTemplate($context['pmx_templatedir'] .'PortaMx');

			// Error request?
			if(!empty($_REQUEST['pmxerror']))
			{
				$context['sub_template'] = 'portamx_error';
				if(in_array($_REQUEST['pmxerror'], array('page', 'article', 'category', 'unknown')))
				{
					$context['pmx_error_title'] = $txt[$_REQUEST['pmxerror'] .'_reqerror_title'];
					$context['pmx_error_text'] = $txt[$_REQUEST['pmxerror'] .'_reqerror_msg'];
				}
				else
				{
					$context['pmx_error_title'] = $txt['download_error_title'];
					if($_REQUEST['pmxerror'] == 'acs')
						$context['pmx_error_text'] = $txt['download_acces_error'];
					elseif($_REQUEST['pmxerror'] == 'fail')
						$context['pmx_error_text'] = $txt['download_notfound_error'];
					else
						$context['pmx_error_text'] = $txt['download_unknown_error'];
				}
			}
		}

		// frontpage set but empty or locked, go to forum
		else
		{
			$_REQUEST['action'] = $_GET['action'] = 'community';

			// setup headers
			PortaMx_headers('community');

			loadTemplate($context['pmx_templatedir'] .'Mainindex');
			$context['template_layers'][] = 'portamx';

			// call the error handler on page/cat/art requests
			if(!empty($context['pmx']['pageReq']))
			{
				loadTemplate($context['pmx_templatedir'] .'PortaMx');
				$context['sub_template'] = 'portamx_error';
				$context['pmx_error_title'] = $txt['front_reqerror_title'];
				$context['pmx_error_text'] = $txt['front_reqerror_msg'];
			}
		}
	}

	else
	{
		// get the action
		$action = (isset($_REQUEST['action']) ? ($_REQUEST['action'] == 'collapse' ? 'community' : $_REQUEST['action']) : (isset($_REQUEST['board']) ? 'boards' : (isset($_REQUEST['topic']) ? 'topics' : '')));

		// get all block on active panels they can view
		$context['pmx']['viewblocks'] = getPanelsToShow($action);

		// load the "Main" template on pages, cats or arts
		if(!empty($context['pmx']['pageReq']))
			loadTemplate($context['pmx_templatedir'] .'PortaMx');

		// setup headers
		PortaMx_headers($action);

		loadTemplate($context['pmx_templatedir'] .'Mainindex');
		$context['template_layers'][] = 'portamx';
	}

	// Setup page title
	loadTemplate($context['pmx_templatedir'] .'Frames');
	$context['page_title'] = $context['forum_name'];

	// build the linktree
	$pmxforum = '';
	if(empty($context['linktree']))
		$context['linktree'] = array(array('url' => $scripturl, 'name' => $mbname));

	$pmxhome[] = array_shift($context['linktree']);
	$inForum = !empty($context['current_board']) || !empty($context['current_topic']) || (!empty($_REQUEST['action']) && in_array($_REQUEST['action'], array('community', 'unread', 'unreadreplies', 'markasread')) || isset($_REQUEST['board']) || isset($_REQUEST['topic']));
	if($context['pmx']['settings']['frontpage'] != 'none' && empty($context['pmx']['pageReq']) && !empty($inForum))
		$pmxhome[] = array('url' => $scripturl . '?action=community', 'name' => $txt['forum']);

	if(!empty($context['pmx']['pageReq']))
	{
		if(!isset($context['pmx']['pagenames']))
			$context['pmx']['pagenames'] = $txt['page_reqerror_title'];

		if(array_key_exists('spage', $context['pmx']['pagenames']))
		{
			$pmxforum[] = array('url' => $scripturl . '?spage='. $_GET['spage'], 'name' => $context['pmx']['pagenames']['spage']);
			$context['page_title'] = $context['pmx']['pagenames']['spage'];
		}
		else
		{
			if(array_key_exists('cat', $context['pmx']['pagenames']))
			{
				$pmxforum[] = array('url' => $scripturl . '?cat='. $_GET['cat'], 'name' => $context['pmx']['pagenames']['cat']);
				$context['page_title'] = $context['pmx']['pagenames']['cat'];
			}
			if(array_key_exists('child', $context['pmx']['pagenames']))
			{
				$pmxforum[] = array('url' => $scripturl . '?cat='. $_GET['cat'] .';child='. $_GET['child'], 'name' => $context['pmx']['pagenames']['child']);
				$context['page_title'] = $context['pmx']['pagenames']['child'];
			}
			if(array_key_exists('art', $context['pmx']['pagenames']))
			{
				$context['page_title'] = $context['pmx']['pagenames']['art'];
				if(array_key_exists('child', $context['pmx']['pagenames']))
					$pmxforum[] = array('url' => $scripturl . '?cat='. $_GET['cat'] .';child='. $_GET['child'] .';art='. $_GET['art'], 'name' => $context['pmx']['pagenames']['art']);
				elseif(array_key_exists('cat', $context['pmx']['pagenames']))
					$pmxforum[] = array('url' => $scripturl . '?cat='. $_GET['cat'] .';art='. $_GET['art'], 'name' => $context['pmx']['pagenames']['art']);
				else
					$pmxforum[] = array('url' => $scripturl . '?art='. $_GET['art'], 'name' => $context['pmx']['pagenames']['art']);
			}
		}
	}

	if(empty($pmxforum))
		$context['linktree'] = array_merge($pmxhome, $context['linktree']);
	else
		$context['linktree'] = array_merge($pmxhome, $pmxforum, $context['linktree']);
}
?>